package com.xxx.demo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.demo.dto.ShowAllDto;
import com.xxx.demo.entity.CustomerEntity;
import com.xxx.demo.entity.ShowType;
import com.xxx.demo.entity.TUsers;
import com.xxx.demo.service.GuestBookService;
import com.xxx.demo.service.NewsService;
import com.xxx.demo.service.ShowService;
import com.xxx.demo.service.ShowTypeService;
import com.xxx.demo.vo.CustomerPageVo;
import com.xxx.demo.vo.ShowAllVo;
import com.xxx.demo.vo.ShowTypeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class ShowController {
    @Value("http://localhost/")
    private String host;
    @Autowired
    private ShowService showService;
    @Autowired
    private ShowTypeService showTypeService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private GuestBookService guestBookService;

    /**
     * 展示分页查询
     * @param showAllDto
     * @param pageNo
     * @param pageSize
     * @param httpSession
     * @param model
     * @return
     */
    @RequestMapping("/findShowAllPage")
    public String findShowAllPage(@ModelAttribute("showAllDto") ShowAllDto showAllDto, Integer pageNo, Integer pageSize, HttpSession httpSession, Model model){
        if (pageNo==null || pageNo<1){
            pageNo=1;
        }
        if (pageSize==null || pageSize<1){
            pageSize=3;
        }
        IPage<ShowAllVo> showAllPage=showService.findShowAllPage(pageNo,pageSize,showAllDto);
        List<ShowAllVo> showAllVos =  showAllPage.getRecords();
        if (CollectionUtil.isNotEmpty(showAllVos)){
            for (ShowAllVo show:showAllVos){
                show.setStrId(show.getId().toString() + "!");
                Date creationDate = show.getCreationDate();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = dateFormat.format(creationDate);
                show.setCreatTime(format);
            }
        }
        showAllPage.setRecords(showAllVos);
        TUsers users= (TUsers) httpSession.getAttribute("user");
        model.addAttribute("adminSession",users);
        model.addAttribute("showAllPage",showAllPage);
        model.addAttribute("showTypes",showTypeService.selectAll());
        return "showPage";
    }

    /**
     * 根据id查详情
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/findShowAllById")
    public String findShowAllById(Model model,Long id,HttpSession session){
        ShowAllVo showAllById = showService.findShowAllById(id);
        model.addAttribute("show",showAllById);
        model.addAttribute("showTypes",showTypeService.selectAll());
        TUsers admin1= (TUsers) session.getAttribute("user");
        model.addAttribute("adminSession",admin1);
        return "updateShow";
    }

    /**
     * 修改
     * @param showAllDto
     * @return
     */
    @RequestMapping("/updateShowAll")
    //@ResponseBody
    public String updateShowAll(ShowAllDto showAllDto,@RequestPart("photo") MultipartFile photo) throws IOException {
        if (StrUtil.isNotEmpty(photo.getOriginalFilename())){
            char point = '.';
            String originalFilename = photo.getOriginalFilename();
            assert originalFilename != null;
            System.out.println(originalFilename);
            System.out.println(originalFilename.lastIndexOf(point));
            String suffix =originalFilename.substring(originalFilename.lastIndexOf(point));
            String fileName= UUID.randomUUID().toString()+suffix;//通过UUID随机生成图片名，防止图片重复
            showAllDto.setShowPhotoUrl("/images/" + fileName);
            photo.transferTo(new File("D:/upload/images/"+fileName));
        }
        showService.updateShowAll(showAllDto);
        return "redirect:findShowAllPage";
        //int i = showService.updateShowAll(showAllDto);
        //if (i == 0){
        //    return "0";
        //}
        //return "1";
    }

    /**
     * 根据id删除（逻辑删除）
     * @param id
     * @return
     */
    @RequestMapping("deleteShowById")
    @ResponseBody
    public String deleteShowById(String id){
        id = id.replace("!","");
        System.out.println(id);
        Long aLong = Long.valueOf(id);
        int i = showService.deleteShowById(aLong);
        if (i == 0){
            return "0";
        }
        return "1";
    }

    /**
     * 查询所有展示类型（用于新增界面）
     * @return
     */
    @RequestMapping("/selectShowTypeAll")
    @ResponseBody
    public List<ShowTypeVo> selectShowTypeAll(){
        List<ShowTypeVo> showTypes = showTypeService.selectAll();
        System.out.println(showTypes);
        //model.addAttribute("showTypes",showTypes);
        return showTypes;
    }

    /**
     * 新增展示
     * @param showAllDto
     * @param photo
     * @return
     * @throws IOException
     */
    @RequestMapping("/addShowAll")
//    @ResponseBody
    public String addShowAll(ShowAllDto showAllDto,@RequestPart("photo") MultipartFile photo) throws IOException {
        String strId = showAllDto.getStrId();
        String replace = strId.replace("!", "");
        System.out.println(replace);
        Long aLong = Long.valueOf(replace);
        System.out.println(aLong);
        showAllDto.setShowTypeId(aLong);
        int i = 0;
        if (ObjectUtil.isNotEmpty(photo)){
            char point = '.';
            String originalFilename = photo.getOriginalFilename();
            assert originalFilename != null;
            String suffix =originalFilename.substring(originalFilename.lastIndexOf(point));
            String fileName= UUID.randomUUID().toString()+suffix;//通过UUID随机生成图片名，防止图片重复
            showAllDto.setShowPhotoUrl("/images/" + fileName);
            photo.transferTo(new File("D:/upload/images/"+fileName));
            i = showService.addShowAll(showAllDto);
        }
        return "redirect:findShowAllPage";
    }



    //============================================以下为客户界面===================================================
    @RequestMapping("/selectSomeShow")
    public String selectSomeShow(Model model,HttpSession session){
        CustomerEntity customerEntity = (CustomerEntity) session.getAttribute("customer");
        if (ObjectUtil.isEmpty(customerEntity)){
            String error = "请先进行登录！！！";
            model.addAttribute("error",error);
            return "index";
        }
        model.addAttribute("customerSession",session.getAttribute("customer"));
        model.addAttribute("showSome",showService.selectSomeShow());
        model.addAttribute("host",host);
        model.addAttribute("showTypes",showTypeService.selectAll());
        model.addAttribute("newsList", newsService.selectAllNews());
        return "customerPage";
    }

    @RequestMapping("/selectSomeShow2")
    public String selectSomeShow2(@ModelAttribute("showAllDto") ShowAllDto showAllDto,Model model,HttpSession session,Integer pageNo,Integer pageSize){
        CustomerEntity customerEntity = (CustomerEntity) session.getAttribute("customer");
        if (ObjectUtil.isEmpty(customerEntity)){
            String error = "请先进行登录！！！";
            model.addAttribute("error",error);
            return "index";
        }
        if (pageNo==null || pageNo<1){
            pageNo=1;
        }
        if (pageSize==null || pageSize<1){
            pageSize=8;
        }
        IPage<ShowAllVo> showAllPage=showService.findShowAllPage(pageNo,pageSize,showAllDto);
        model.addAttribute("customerSession",session.getAttribute("customer"));
        model.addAttribute("showAllPage",showAllPage);
        model.addAttribute("host",host);
        model.addAttribute("showTypes",showTypeService.selectAll());
        model.addAttribute("newsList", newsService.selectAllNews());
        return "customerIPage";
    }

    @RequestMapping("/findShowById")
    public String findShowById(Long showId,Model model,HttpSession session){
        model.addAttribute("customerSession",session.getAttribute("customer"));
        model.addAttribute("showAll",showService.findShowById(showId));
        model.addAttribute("showTypes",showTypeService.selectAll());
        model.addAttribute("newsList", newsService.selectAllNews());
        model.addAttribute("guestBooks",guestBookService.queryGuestBook());
        return "showById";
    }

    @RequestMapping("/findShowByTypeId")
    public String findShowByTypeId(Long showTypeId,Model model,HttpSession session){
        CustomerEntity customerEntity = (CustomerEntity) session.getAttribute("customer");
        if (ObjectUtil.isEmpty(customerEntity)){
            String error = "请先进行登录！！！";
            model.addAttribute("error",error);
            return "index";
        }
        model.addAttribute("customerSession",session.getAttribute("customer"));
        model.addAttribute("shows",showService.findShowByTypeId(showTypeId));
        model.addAttribute("showTypes",showTypeService.selectAll());
        model.addAttribute("newsList", newsService.selectAllNews());
        return "customerPage2";
    }

}
